﻿using System;

namespace XNWebService
{
    public class Distance
    {
        public static double DEGREES_TO_RADIANS = Math.PI / 180.0;
        public static double RADIANS_TO_DEGREES = 180.0 / Math.PI;
        //地球半径
        public static double EARTH_MEAN_RADIUS_KM = 6371.009;
        //地球直径
        private static double EARTH_MEAN_DIAMETER = EARTH_MEAN_RADIUS_KM * 2;

        /// <summary>
        /// 两坐标[经纬度]之间的距离
        /// </summary>
        /// <param name="lon1">经度1</param>
        /// <param name="lat1">纬度1</param>
        /// <param name="lon2">经度2</param>
        /// <param name="lat2">纬度2</param>
        /// <returns>两坐标的距离 单位千米</returns>
        public static double TwoLonLatDistance(double lat1, double lon1, double lat2, double lon2)
        {
            //计算经纬度
            double latRad = lat2 * DEGREES_TO_RADIANS;
            double lonRad = lon2 * DEGREES_TO_RADIANS;

            //计算经纬度的差
            double diffX = lat1 * DEGREES_TO_RADIANS - latRad;
            double diffY = lon1 * DEGREES_TO_RADIANS - lonRad;
            //计算正弦和余弦
            double hsinX = Math.Sin(diffX * 0.5);
            double hsinY = Math.Sin(diffY * 0.5);
            double latCenterRad_cos = Math.Cos(lat1 * DEGREES_TO_RADIANS);
            double h = hsinX * hsinX + (latCenterRad_cos * Math.Cos(latRad) * hsinY * hsinY);

            return (EARTH_MEAN_DIAMETER * Math.Atan2(Math.Sqrt(h), Math.Sqrt(1 - h)));
        }

    }
}